package com.jiangyg.mall.authz.config;

import com.jiangyg.mall.authz.MemberInfoHolder;
import com.jiangyg.mall.authz.UserInfoHolder;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：安全认证自动配置
 * <p>项目依赖 mall-authz-api 模块时，会自动启用 {@link com.jiangyg.mall.authz.config.AuthzAutoConfiguration} 配置，
 * 主要用来追加清除用户信息的拦截器</p>
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-09
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class AuthzAutoConfiguration implements WebMvcConfigurer {

    /**
     * 功能描述：追加清空认证信息上下文
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                Logger.debug(log, () -> String.format("[请求预处理]-清空请求[%s]认证信息上下文", WebUtils.getRequestPath(request)));
                this.clean();
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                Logger.debug(log, () -> String.format("[请求完毕处理]-清空请求[%s]认证信息上下文", WebUtils.getRequestPath(request)));
                this.clean();
            }

            /**
             * 功能描述：清空后台和会员的用户信息
             */
            private void clean() {
                UserInfoHolder.clearContext();
                MemberInfoHolder.clearContext();
            }

        });
    }

}
